package cevent.source.cloudcenter.server.service;

import cevent.source.cloudcenter.server.domain.Address;
import cevent.source.cloudcenter.server.domain.AddressExample;
import cevent.source.cloudcenter.server.dto.AddressCityDto;
import cevent.source.cloudcenter.server.dto.AddressDto;
import cevent.source.cloudcenter.server.dto.PageDto;
import cevent.source.cloudcenter.server.mapper.AddressMapper;
import cevent.source.cloudcenter.server.util.DuplicateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cevent
 * @description 城市地区服务层
 */
@Service
public class AddressService {
    private static final Logger LOG=LoggerFactory.getLogger(AddressService.class);
    @Resource
    private AddressMapper addressMapper;

    //1.无分页列表查询：dto获取domain参数
    public List<AddressDto> addressDtoList(){
        AddressExample addressExample = new AddressExample();
        addressExample.setOrderByClause("uni_id asc");
        List<Address> addressList=addressMapper.selectByExample(addressExample);
        List<AddressDto> addressDtoList = new ArrayList<AddressDto>();
        for(int i=0;i<addressList.size();i++){
            Address address=addressList.get(i);
            AddressDto addressDto=new AddressDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(address,addressDto);
            addressDtoList.add(addressDto);
        }
        return addressDtoList;
    }

    //树形tree结构
    public List<AddressDto> getAreaListWithTree(){
        AddressExample addressExample=new AddressExample();
        addressExample.setOrderByClause("id asc");
        List<Address> addressList=addressMapper.selectByExample(addressExample);
        List<AddressDto> addressDtoList=DuplicateUtil.copyList(addressList,AddressDto.class);
        //过滤以及省份parentId=0，必须新增一个list来接收过滤参数
        List<AddressDto> addr= addressDtoList.stream().filter((add)->{
            return add.getParentid().equals(0);
        }).map((addChild)->{ //map映射子菜单
            addChild.setChildren(getAddChildren(addressDtoList,addChild));
            return addChild;
        }).collect(Collectors.toList());

        return addr;
    }
    //递归查询：传入当前区域，获取子区域。传入所有区域，从区域中筛选子菜单
    private List<AddressDto> getAddChildren(List<AddressDto> addressDtoList,AddressDto addressDto){
        List<AddressDto> addDto =addressDtoList.stream().filter((addressDto1)->{
            //当前菜单的父id=传入菜单的id，为父级
            return addressDto1.getParentid().equals(addressDto.getId());
        }).map((child)->{ //存在子区域，获取子区域。并将当前区域和传入的list再次返回，进行递归查询
            child.setChildren(getAddChildren(addressDtoList,child));
            return child;
        }).collect(Collectors.toList());
        return addDto;
    }
    //获取城市
    public List<String> getCities(){
        AddressExample addressExample=new AddressExample();
        addressExample.setOrderByClause("id asc");
        List<Address> addressList=addressMapper.selectByExample(addressExample);
        List<String> addressCityDtos=new ArrayList<>();
        addressList.stream().forEach(address->{
            if(address.getParentid()>0){
                AddressCityDto addressCityDto=new AddressCityDto();
                addressCityDto.setId(String.valueOf(address.getId()));
                addressCityDto.setAreaname(address.getAreaname());
                addressCityDto.setLevel("");
                addressCityDto.setParentid(String.valueOf(address.getParentid()));
                //转JSON
                JSONObject jsonObject=(JSONObject) JSONObject.toJSON(addressCityDto);
                String addCityStr=jsonObject.toJSONString();
                addressCityDtos.add(addCityStr);
            }

        });
        LOG.info("获取所有城市：{}",addressCityDtos);

        return addressCityDtos;
    }
    /*2.分页查询：pageDto保存数据
        list数据集合：listPageData
        当前页码：currentPage
        每页行数：size
        总计函数：totalSize
        前端可返回pageDto，无需返回值
     */
    public void getAddressPageDtoList(PageDto pageDto){
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(pageDto.getCurrentPage(),pageDto.getSize());

        AddressExample addressExample=new AddressExample();


        List<Address> addressList=addressMapper.selectByExample(addressExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Address> pageInfo=new PageInfo<>(addressList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        pageDto.setTotalSize(pageInfo.getTotal());

        List<AddressDto> addressDtoList=new ArrayList<>();
        addressList.stream().forEach(address->{
            AddressDto addressDto=new AddressDto();
            BeanUtils.copyProperties(address,addressDto);
            addressDtoList.add(addressDto);
        });

        pageDto.setListPageData(addressDtoList);

    }

    //3.新增、修改address，将传入的id转为address对象本身
    public void save(AddressDto addressDto){
        Address address= DuplicateUtil.copy(addressDto,Address.class);
        if(StringUtils.isEmpty(addressDto.getId())){
            this.insert(address);
        }else{
            this.update(address);
        }

    }

    //4.删除模块
    public void delete(Integer uniId){
        AddressExample addressExample=new AddressExample();
        addressMapper.deleteByPrimaryKey(uniId);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Address address){

        try {
        Date now =new Date();
        String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
        long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
        int timeInt=(int)(time/1000);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        addressMapper.insert(address);
    }

    //6.更新模块
    private void update(Address address){
        try {
            Date now =new Date();
            String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt=(int)(time/1000);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        addressMapper.updateByPrimaryKey(address);
    }



}
